//
//  ViewController.m
//  MyDemo
//
//  Created by Admin on 2017/11/10.
//  Copyright © 2019年 Admin. All rights reserved.
//
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>

#import "promotionViewC.h"

#import "../MKConstant.h"
#import "../network.h"
#import "../Utils/DataPersist.h"

@interface promotionViewC () <UITableViewDelegate,UITableViewDataSource,WKUIDelegate,WKNavigationDelegate>
{
    CGFloat wkWebViewHeight;
    
    NSData *itemHTMLData;
}

@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UITableView *tableView;
@property (strong, nonatomic)   UIProgressView              *progressView;

@end

@implementation promotionViewC

- (void)dealloc {
    //    [self removeWebViewObserver];
}
#pragma mark ------ < Life Cycle > ------
#pragma mark
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self initializeDataSource];
    [self initializeUserInterface];
    
    // 颜色
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor whiteColor];
    //NSString *title = self.itemDatasource.title;
    //NSString *title = @"1";
    //NSString *title = self.itemDatasource;
    //self.navigationItem.title = title;  //设置navigationItem.title 标题
    [self.navigationController.navigationBar setTitleTextAttributes:@{
                                                                      NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor grayColor]                }];
    
    //网络初始化
    //等网络请求 通知后再加载数据
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setitemdata) name:@"getitemDataNOTIF" object:nil];
    
    network *getdata = [[network alloc]init];
    [getdata itemVcgetJsonData:@"promotionid" item:@"389"];  //获取子页面数据
   // [self loadingView];  //等待网络结果动画
    
    
    // sv 空白
    //    self.automaticallyAdjustsScrollViewInsets = false;
    //    UIView *view_head = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH*0.6)];
    //    view_head.backgroundColor = [UIColor whiteColor];
    //    [self.view addSubview:view_head];
//    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(rightClick)];
//    self.navigationItem.rightBarButtonItem = rightItem;
    
    // [self setitemdata];  不等网络请求直接加载数据
    
    
}

-(void)setitemdata{
    //读取数组值
    NSMutableArray *itemArray = [[DataPersist readValueNSMutableArray:@"itemData"] mutableCopy];
//    NSMutableArray *itemArray = [[NSMutableArray alloc] init];
    //NSLog(@"itemArray %@ ",itemArray);
   
    
    NSDictionary *itemdata = [itemArray valueForKey:@"data"];
    //NSLog(@"itemdata is %@",itemdata);
    
    NSString *banner = [itemdata valueForKey:@"top_desc"];
    //NSLog(@"banner is %@",banner);
    
    NSString *post_content = [itemdata valueForKey:@"middle_desc"];
    //NSLog(@"post_content is %@",post_content);
    
    NSMutableString *headHTML = [NSMutableString string];  //加载本地CSS js
    [headHTML appendString:@"<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\">"];
    [headHTML appendFormat:@"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"%@\" />",[[NSBundle mainBundle] URLForResource:@"style" withExtension:@"css"]];
    
    [headHTML appendFormat:@"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"%@\" />",[[NSBundle mainBundle] URLForResource:@"w3" withExtension:@"css"]];
    
    [headHTML appendString:@"</head><body>"];
    
    
    banner = [headHTML stringByAppendingString:banner]; //合并banner 和 post_content
    
    NSString *str2 = [banner stringByAppendingString:post_content]; //合并banner 和 post_content
    //NSLog(@"str2 is %@",str2);
    
    
    itemHTMLData = [str2 dataUsingEncoding:NSUTF8StringEncoding];
    
    //banner
    //    homebannerarr = [dataarr valueForKey:@"homeBanner"];
    //    NSLog(@"homeBannerarr is %@",homebannerarr);
    //    //NSLog(@"imgbanner url %@",homebannerarr[1]);
    //
    //    //字典   包含数组
    //    NSMutableArray *aceServicesarr = [dataarr valueForKey:@"aceServices"];
    //    NSArray *arra = [self setnewarr:aceServicesarr cate:@"aceServices"];
    //    //NSLog(@"arra %@",arra);
    //
    //    NSMutableArray *healthManagementarr = [dataarr valueForKey:@"healthManagement"];
    //    NSArray *arrb = [self setnewarr:healthManagementarr cate:@"healthManagement"];
    //
    //
    //    NSMutableArray *menuarr2 = [[NSMutableArray alloc]init]; //菜单数组新建
    //    [menuarr2 addObject:arra];
    //    [menuarr2 addObject:arrb];
    //NSLog(@"menuarr.count %lu",(unsigned long)menuarr2.count);
    
    //menuarr = [menuarr2 mutableCopy];
    
    //NSLog(@"menuarr.count %lu",(unsigned long)menuarr.count);
    //NSLog(@"menuarr %@",menuarr2);
    
    
    //NSLog(@"第一次读取的值MACArray value is:%@",MACArray);
    
    //        NSMutableArray *dataarr = [MACArray valueForKey:@"data"];
    //
    //    NSString *item3 = [homeBannerarr firstObject];
    //    //NSLog(@"item3  %@",item3);
    //    [DataPersist writeValuePre:item3 key:@"banner1"];
    
   // [self startInitWKWebView];
}

-(void)loadingView{  //等待网络结果动画
    
    CGRect frame = CGRectMake(0, 0, 100, 100);
    UIView *activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg.center = self.view.center;
    activityBg.backgroundColor = [UIColor grayColor];
    activityBg.alpha = 0.7;
    activityBg.layer.cornerRadius = 5.0;
    //[self.view addSubview:activityBg];
    [self.view addSubview:activityBg];
    
    UIActivityIndicatorView *loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loadActivity.frame = CGRectMake(30, 30, 40, 40);
    [loadActivity sizeToFit];
    loadActivity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [activityBg addSubview:loadActivity];
    [loadActivity startAnimating];
    //     //网络请求 延迟时间
    //    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 5000*NSEC_PER_MSEC);
    //    // 延迟方法
    //    // 1 delayTime 2 thread 3 代码
    //    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
    //        [loadActivity stopAnimating];
    //        [activityBg removeFromSuperview];
    //        [self dismissViewControllerAnimated:true completion:nil];
    ////        [self setindexdata]; //设置首页数据
    ////        [self setMenuData];
    ////        [self settableView];
    //    });
    
}

#pragma mark ------ < Initialize > ------
#pragma mark
- (void)initializeDataSource {
    
}

- (void)initializeUserInterface {
    [self.view addSubview:self.tableView];
    [self setupWebView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ------ < Request > ------
#pragma mark

#pragma mark ------ < Event Response > ------
#pragma mark

#pragma mark ------ < Private Method > ------
#pragma mark
- (void)setupWebView {
    wkWebViewHeight = 0.f;
    //NSURL *url = [NSURL URLWithString:@"https://www.jianshu.com/p/22f39afdaa44"];
//    NSURL *url = [NSURL URLWithString:@"http://youngplus.com.hk/app-get-promotions?id=389"];
//    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
//    [self.wkWebView loadRequest:urlRequest];
    
    //////    [self addWebViewObserver];
    
    //    // 将请求到的网页数据用loadHTMLString 的方法加载
    NSString *htmlStr = [[NSString alloc] initWithData:itemHTMLData encoding:NSUTF8StringEncoding];
    NSLog(@"htmlStr %@",htmlStr);
    
    NSURL *baseUrl = [NSURL URLWithString:@"file:///assets/"];
    //[self.webView loadHTMLString:[self.viewModel getHtmlString] baseURL:baseUrl];
    [self.wkWebView loadHTMLString:htmlStr baseURL:baseUrl];
    
    self.wkWebView.navigationDelegate = self;
    self.wkWebView.UIDelegate = self;
    [self.view addSubview:self.wkWebView];
}

/** < 方式一 > */
//- (void)addWebViewObserver {
//    [self.wkWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
//}

//- (void)removeWebViewObserver {
//    [self.wkWebView.scrollView removeObserver:self forKeyPath:@"contentSize"];
//}

//#pragma mark ------ < KVO > ------
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//    /**  < 法2 >  */
//    /**  < loading：防止滚动一直刷新，出现闪屏 >  */
//    if ([keyPath isEqualToString:@"contentSize"]) {
//        CGRect webFrame = self.wkWebView.frame;
//        webFrame.size.height = self.wkWebView.scrollView.contentSize.height;
//        self.wkWebView.frame = webFrame;
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:3 inSection:0], nil] withRowAnimation:UITableViewRowAnimationNone];
//    }
//}

#pragma mark ------ < UITableViewDelegate,UITableViewDataSource > ------
#pragma mark
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 3:
            return self.wkWebView.frame.size.height;
            break;
        default:
            return 50;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 3:
        {
            UITableViewCell *webCell = [tableView dequeueReusableCellWithIdentifier:@"WebViewCell" forIndexPath:indexPath];
            [webCell.contentView addSubview:self.wkWebView];
            return webCell;
        }
            break;
        default:
        {
            UITableViewCell *defaultCell = [tableView dequeueReusableCellWithIdentifier:@"DefaultCell" forIndexPath:indexPath];
            defaultCell.textLabel.text = [NSString stringWithFormat:@"普通的cell，编号：%ld", indexPath.row];
            return defaultCell;
        }
            break;
    }
}

#pragma mark ------ < UIScrollViewDeltegate > ------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    /**  < 解决web白屏问题 >  */
    /**  < 需要调用私有API：_updateVisibleContentRects >  */
    [self.wkWebView setNeedsLayout];
}

#pragma mark ------ < WKUIDelegate,WKNavigationDelegate > ------
#pragma mark
/**  < 法2 >  */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    //document.body.offsetHeight
    //document.body.scrollHeight
    //document.body.clientHeight
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        CGFloat documentHeight = [result doubleValue];
        CGRect webFrame = webView.frame;
        webFrame.size.height = documentHeight;
        webView.frame = webFrame;
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:3 inSection:0], nil] withRowAnimation:UITableViewRowAnimationNone];
    }];
    
    
    //    CGRect webFrame = self.wkWebView.frame;
    //    CGFloat contentHeight = webView.scrollView.contentSize.height;
    //    webFrame.size.height = contentHeight;
    //    webView.frame = webFrame;
    //    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:3 inSection:0], nil] withRowAnimation:UITableViewRowAnimationNone];
}

//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//    if (navigationAction.navigationType == WKNavigationTypeOther) {
//        if ([[[navigationAction.request URL] scheme] isEqualToString:@"ready"]) {
//            float contentHeight = [[[navigationAction.request URL] host] floatValue];
//            CGRect webFrame = self.wkWebView.frame;
//            webFrame.size.height = contentHeight;
//            webView.frame = webFrame;
//
//            NSLog(@"onload = %f",contentHeight);
//
//            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:3 inSection:0], nil] withRowAnimation:UITableViewRowAnimationNone];
//
//            decisionHandler(WKNavigationActionPolicyCancel);
//            return;
//        }
//    }
//    decisionHandler(WKNavigationActionPolicyAllow);
//}

#pragma mark ------ < getter > ------
#pragma mark
- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        wkWebConfig.userContentController = wkUController;
        /** << 自适应屏幕宽度js > */
        NSMutableString *JSString = [NSMutableString string];
        
        /** < 法3 > */
        NSString *windowLocationString = @"<script type=\"text/javascript\">\
        window.onload = function() {\
        window.location.href = \"ready://\" + document.body.scrollHeight;\
        }\
        </script>";
        
        [JSString appendString:windowLocationString];
        
        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        
        [JSString appendString:jSString];
        
        
        WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:JSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        /** << 添加js调用 > */
        [wkUController addUserScript:wkUserScript];
        _wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 1) configuration:wkWebConfig];
        _wkWebView.UIDelegate = self;
        _wkWebView.navigationDelegate = self;
        _wkWebView.opaque = NO;
        _wkWebView.scrollView.scrollEnabled = NO;
        _wkWebView.scrollView.showsVerticalScrollIndicator = NO;
        if (@available(iOS 11.0,*)) {
            _wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _wkWebView.scrollView.bounces = NO;
        _wkWebView.backgroundColor = [UIColor clearColor];
    }
    return _wkWebView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 50.f;
        if (@available(iOS 11.0,*)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"WebViewCell"];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"DefaultCell"];
    }
    return _tableView;
}


@end
